<template>
  <div class="index">
    <div class="write">
      <div class="slidedown" @click="slide">
        <p class="innerit el-icon-lx-tag"> 写点动态吧~</p>
      </div>
      <div style="border: 1px dashed #dadada;padding: 5px;display: none;width: 700px;" class="container" id="slideed"
           check="1">
        <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="textarea"
            maxlength="500"
            show-word-limit
            :rows="5"
        >
        </el-input>
        <div style="margin: 5px 0;"></div>
        <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            ref="upload"
            :limit="limit"
            :on-exceed="moreout"
            :on-change="handleChange"
            :multiple="true"
            style="height: 148px;border: 1px dashed #eaeaea;padding: 5px;margin-top: 10px;">
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}">
            <img
                class="el-upload-list__item-thumbnail"
                :src="file.url" alt=""
            >
            <span class="el-upload-list__item-actions">
          <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)"
          >
          <i class="el-icon-zoom-in"></i>
          </span>
          <span
              v-if="!disabled"
              class="el-upload-list__item-delete"
              @click="handleRemove(file)"
          >
            <i class="el-icon-delete"></i>
          </span>
         </span>
          </div>
        </el-upload>
        <div style="display: flex;justify-content: right;align-items: center">
          <el-button type="danger" :loading="isLoading" @click.native.prevent="uploadChats" icon="el-icon-position"
                     circle>xiu~
          </el-button>
        </div>
      </div>
    </div>
    <el-empty v-if="isGet" description="文章为空"></el-empty>
    <el-card class="box-card card" v-else body-style="padding:20px 20px 5px 20px" v-for="(item,index) in dynamicInfo"
             :key="index">
      <div v-if="item.isShare"
           style="width: 700px;display: flex;flex-direction:column;justify-content: center;align-items: center;">
        <div class="header" style="justify-content: space-between">
          <div class="header">
            <div class="logo" @click="toShowModel(item.uid)">
              <el-avatar :class="{'logodiv':item.isDoctor}" :src="item.ShareManInfo.logoPath"></el-avatar>
            </div>
            <div class="name">
              <span style="font-size: 18px;font-weight: bolder;font-family: 宋体">{{ item.ShareManInfo.userName }}</span>
              <span style="color: #c5baba">{{ item.shareManDate }}</span>
            </div>
            <img width="30px" v-if="!item.isDoctor" title="专家" height="30px" src="../assets/金牌-2.png"/>
          </div>
        </div>
        <div style="background-color:#e3dfdf;margin: 10px">
          <div class="header" style="width: 600px;justify-content: space-between">
            <div class="header">
              <div class="logo">
                <el-avatar :src="item.logoPath"></el-avatar>
              </div>
              <div class="name">
                <span style="font-size: 18px;font-weight: bolder;font-family: 宋体">{{ item.userName }}</span>
                <span style="color: #c5baba">{{ item.creatDate }}</span>
              </div>
              <img width="30px" v-if="item.isDoctor" title="专家" height="30px" src="../assets/金牌-2.png"/>
            </div>
          </div>
          <div class="article" style="width: 600px" v-html="item.dynamic"></div>
          <div class="picture" style="width: 600px" v-if="item.isPicture">
            <img v-for="(itt,ind) in item.imgArr" :key="ind" :src="itt.src" style="margin-right: 5px;cursor: pointer;"
                 height="150px" width="200px" @click="showDetail(itt.id)"/>
          </div>
        </div>
        <div style="clear: both"></div>
      </div>
      <div style="width: 700px" v-if="!item.isShare">
        <div class="header" style="justify-content: space-between">
          <div class="header">
            <div :class="{'logo':true,'logodiv':item.isDoctor}" @click="toShowModel(item.uid)">
              <el-avatar :src="item.logoPath"></el-avatar>
            </div>
            <div class="name">
              <span style="font-size: 18px;font-weight: bolder;font-family: 宋体">{{ item.userName }}</span>
              <span style="color: #c5baba">{{ item.creatDate }}</span>
            </div>
          </div>
          <img width="30px" v-if="item.isDoctor" title="专家" height="30px" src="../assets/金牌-2.png"/>
        </div>
        <div class="article" v-html="item.dynamic"></div>
        <div class="picture" v-if="item.isPicture">
          <img v-for="(itt,ind) in item.imgArr" :key="ind" :src="itt.src" style="margin-right: 5px;cursor: pointer;"
               height="150px" width="200px" @click="showDetail(itt.id)"/>
        </div>
        <div class="operation">
          <div style="display: flex;justify-content: center;align-items: center;margin-right: 20px;">
            <div :class="{'thumbs_up':!item.isClick,'thumbs_up_red':item.isClick}" @click="clickbest(item.id)"></div>
            <div style="height: 20px;width: 20px;line-height: 24px;text-align: center">{{ item.count }}</div>
          </div>
          <div class="share" @click="share(item.id)"></div>
        </div>
      </div>
    </el-card>
    <div id="mask" v-if="isPay" @click="isPay = false,detail=''">
      <img height="100%" :src="detail">
    </div>

    <el-dialog
        title="用户操作"
        :visible.sync="centerDialogVisible"
        width="20%"
        center>
      <div style="width: 100%;">
        <el-button type="primary" plain @click="addFriend()">添加关注</el-button>
        <el-button plain @click="toTalk()">聊天界面</el-button>
        <el-button plain @click="toCross()">申请好友</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import $ from 'jquery'
import {MessageBox} from "element-ui";


export default {
  name: "Index",
  data: function () {
    return {
      dynamicInfo: [],
      limit: 3,
      dialogImageUrl: '',
      filearr: [],
      disabled: false,
      param: null,
      textarea: "",
      isLoading: false,
      isPay: false,
      detail: "",
      fullscreenLoading: false,
      isGet: false,
      keywords: "",
      centerDialogVisible: false,
      addUid: null
    }
  },
  mounted() {
    this.getDynamic()
  },
  watch: {
    '$store.state.keywords': function (e) {
      this.getDynamicByKeywords(e)
    }
  },
  methods: {
    isDoctor(id) {
      return new Promise(resolve => {
        this.$http.get("/doctor/isDoctor/" + id).then(res => {
          resolve(res.data)
        })
      })
    },
    addFriend() {
      this.$http.put("/friend/insertFriend/" + this.addUid).then(data => {
        if (data.code == 200) {
          this.$message.success("添加成功")
          this.centerDialogVisible = false
        } else if (data.code == 501) {
          this.$message.error(data.message)
          this.centerDialogVisible = false
        }
      })
    },
    toTalk() {
      this.$router.push({
        path: '/friend',
        query: {
          touser: this.addUid,
        }
      });
    },
    toCross() {
      // let param = {
      //   crossId: this.addUid
      // }
      // this.$http.post("/cross/add",param).then(data => {
      //   if (data.code == 200) {
      //     this.$message.success("申请成功")
      //     this.centerDialogVisible = false
      //   } else if (data.code == 501) {
      //     this.$message.error(data.message)
      //     this.centerDialogVisible = false
      //   }
      // })
    },
    toShowModel(id) {
      this.centerDialogVisible = true
      this.addUid = id
    },
    clickbest(id) {
      let token = window.localStorage.getItem('myToken');
      if (token == null) {
        this.$message.error("请登录后点赞！！")
        return
      }
      this.$http.put("/likeAndComment/likeOrCancel/" + id).then(res => {
        if (res.code == 200) {
          let arr = JSON.parse(JSON.stringify(this.dynamicInfo))
          arr.filter(async (item) => {
            await this.getBestCountWithRId(item.id).then(res => {
              item.count = res
            })
            await this.checkWeatherIsSelected(item.id).then(res => {
              item.isClick = res
            })

          })
          this.dynamicInfo = arr
        }

      })
    },
    checkWeatherIsSelected(rid) {
      return new Promise(resolve => {
        this.$http.get("/likeAndComment/checkWeatherIsSelected/" + rid).then(data => {
          resolve(data.data)
        })
      })
    },
    getBestCountWithRId(rid) {
      return new Promise(resolve => {
        this.$http.get("/likeAndComment/getBestCountWithRId/" + rid).then(data => {
          resolve(data.data)
        })
      })
    },
    share(id) {
      MessageBox('是否分享', '分享提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.get("/dynamic/shareDynamic/" + id).then(data => {
          console.log(data)
          if (data.code == 200) {
            this.getDynamic()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消分享'
        });
      });
    },
    showDetail(id) {
      this.getImgDetail(id).then(res => {
        this.detail = res
      })
      this.isPay = !this.isPay;
    },
    uploadChats() {
      if (this.filearr.length == 0) {
        this.uploadDynamic("")
        return
      }
      this.param = new FormData()
      this.filearr.forEach((file) => {
        this.param.append(`file`, file) // 把单个文件重命名，存储起来（给后台）
      })
      this.$http({
        method: "post",
        url: "/dynamic/insertDynamicImg",
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        data: this.param
      }).then(data => {
        this.uploadDynamic(data.data)
      })
    },
    uploadDynamic(ids) {
      let idsarr = []
      if (ids != "") {
        for (let i = 0; i < ids.length; i++) {
          idsarr.push(ids[i].id)
        }
      }
      let data = {
        dynamic: this.textarea,
        imgId: idsarr
      }
      console.log(data)
      var that = this
      this.$http.post("/dynamic/uploadDynamic", data).then(data => {
        if (data.code == 200) {
          that.$message.success("上传成功")
          that.$refs.upload.clearFiles();
          that.textarea = ""
          that.getDynamic()
          $("#slideed").slideUp();
        }
      })
    },
    async getDynamicByKeywords(keywords) {
      await this.$http.post("/dynamic/keywordsSearch", {keywords: keywords}).then(async data => {
        if (data.data.length == 0) {
          this.isGet = true
          return
        }
        data = data.data
        for (let i = 0; i < data.length; i++) {
          if (data[i].isShare) {
            await this.getUserBasicsInfo(data[i].shareManId).then(async res => {
              data[i].ShareManInfo = res
              await this.getImg(res.logo).then(rt => {
                data[i].ShareManInfo.logoPath = rt
              })

            })
            if (data[i].imgId == null) {
              data[i].isPicture = false
            } else {
              data[i].isPicture = true
              data[i].imgArr = []
              for (let j = 0; j < data[i].imgId.length; j++) {
                let json = {
                  src: "",
                  id: ""
                }
                await this.getImgCompress(data[i].imgId[j]).then(res => {
                  json.src = res
                  json.id = data[i].imgId[j]
                  data[i].imgArr.push(json)
                })
              }
            }
            await this.getUserBasicsInfo(data[i].uid).then(async res => {
              data[i].userName = res.userName
              await this.getImg(res.logo).then(res => {
                data[i].logoPath = res
              })
            })
          } else {
            await this.checkWeatherIsSelected(data[i].id).then(res => {
              data[i].isClick = res
            })
            await this.getBestCountWithRId(data[i].id).then(res => {
              data[i].count = res
            })
            if (data[i].imgId == null) {
              data[i].isPicture = false
            } else {
              data[i].isPicture = true
              data[i].imgArr = []
              for (let j = 0; j < data[i].imgId.length; j++) {
                let json = {
                  src: "",
                  id: ""
                }
                await this.getImgCompress(data[i].imgId[j]).then(res => {
                  json.src = res
                  json.id = data[i].imgId[j]
                  data[i].imgArr.push(json)
                })
              }
            }
            await this.getUserBasicsInfo(data[i].uid).then(async res => {
              data[i].userName = res.userName
              await this.getImg(res.logo).then(res => {
                data[i].logoPath = res
              })
            })
          }
        }
        this.dynamicInfo = data
      })
    },
    async getDynamic() {
      await this.$http.get("/dynamic/getDynamicAll").then(async data => {
        console.log(data)
        if (data.data.length == 0) {
          this.isGet = true
          return
        }
        data = data.data
        for (let i = 0; i < data.length; i++) {
          if (data[i].isShare) {
            await this.getUserBasicsInfo(data[i].shareManId).then(async res => {
              data[i].ShareManInfo = res
              await this.getImg(res.logo).then(rt => {
                data[i].ShareManInfo.logoPath = rt
              })
              await this.isDoctor(data[i].shareManId).then(res => {
                data[i].ShareManInfo.isDoctor = res
              })
            })
            if (data[i].imgId == null) {
              data[i].isPicture = false
            } else {
              data[i].isPicture = true
              data[i].imgArr = []
              for (let j = 0; j < data[i].imgId.length; j++) {
                let json = {
                  src: "",
                  id: ""
                }
                await this.getImgCompress(data[i].imgId[j]).then(res => {
                  json.src = res
                  json.id = data[i].imgId[j]
                  data[i].imgArr.push(json)
                })
              }
            }
            await this.isDoctor(data[i].uid).then(res => {
              data[i].isDoctor = res
            })
            await this.getUserBasicsInfo(data[i].uid).then(async res => {
              data[i].userName = res.userName
              await this.getImg(res.logo).then(res => {
                data[i].logoPath = res
              })
            })
          } else {
            await this.isDoctor(data[i].uid).then(res => {
              data[i].isDoctor = res
            })
            await this.checkWeatherIsSelected(data[i].id).then(res => {
              data[i].isClick = res
            })
            await this.getBestCountWithRId(data[i].id).then(res => {
              data[i].count = res
            })
            if (data[i].imgId == null) {
              data[i].isPicture = false
            } else {
              data[i].isPicture = true
              data[i].imgArr = []
              for (let j = 0; j < data[i].imgId.length; j++) {
                let json = {
                  src: "",
                  id: ""
                }
                await this.getImgCompress(data[i].imgId[j]).then(res => {
                  json.src = res
                  json.id = data[i].imgId[j]
                  data[i].imgArr.push(json)
                })
              }
            }
            await this.getUserBasicsInfo(data[i].uid).then(async res => {
              data[i].userName = res.userName
              await this.getImg(res.logo).then(res => {
                data[i].logoPath = res
              })
            })
          }
        }
        this.dynamicInfo = data
      })
      this.isGet = false
    },
    getUserBasicsInfo(id) {
      return new Promise(resolve => {
        this.$http.get("/user/getUserBasicsInfo/" + id).then(data => {
          resolve(data.data)
        })
      })
    },
    getImg(id) {
      return new Promise(resolve => {
        this.$http({
          url: "/file/img/" + id,
          method: "get",
          responseType: "arraybuffer",
        }).then(res => {
          let bytes = new Uint8Array(res);
          let storeData = "";
          let len = bytes.byteLength;
          for (let i = 0; i < len; i++) {
            storeData += String.fromCharCode(bytes[i]);
          }
          let database = "data:image/png;base64," + window.btoa(storeData);
          resolve(database);
        });
      })
    },
    getImgCompress(id) {
      return new Promise(resolve => {
        this.$http({
          url: "/dynamic/downloadCompress/" + id,
          method: "get",
          responseType: "arraybuffer",
        }).then(res => {
          let bytes = new Uint8Array(res);
          let storeData = "";
          let len = bytes.byteLength;
          for (let i = 0; i < len; i++) {
            storeData += String.fromCharCode(bytes[i]);
          }
          let database = "data:image/png;base64," + window.btoa(storeData);
          resolve(database);
        });
      })
    },
    getImgDetail(id) {
      return new Promise(resolve => {
        this.$http({
          url: "/dynamic/download/" + id,
          method: "get",
          responseType: "arraybuffer",
        }).then(res => {
          let bytes = new Uint8Array(res);
          console.log(bytes)
          let storeData = "";
          let len = bytes.byteLength;
          for (let i = 0; i < len; i++) {
            storeData += String.fromCharCode(bytes[i]);
          }
          let database = "data:image/png;base64," + window.btoa(storeData);
          resolve(database);
        });
      })
    },
    slide() {
      let token = window.localStorage.getItem('myToken');
      if (token == null || this.iden == "游客") {
        this.$message.error('请登陆或注册或者认证身份');
        return
      }
      let check = $("#slideed").attr("check");
      if (check == "1") {
        $("#slideed").slideDown();
        $("#slideed").attr("check", "2")
      } else {
        $("#slideed").slideUp();
        $("#slideed").attr("check", "1")
      }
    },
    handleChange(file) {
      const fileObj = file.raw;
      if (file && fileObj) {
        this.filearr.push(fileObj)
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
    },
    moreout() {
      this.$message.warning("最多上传三张照片！")
    },
    handleRemove(file) {
      let fileList = this.$refs.upload.uploadFiles;
      let index = fileList.findIndex(fileItem => {
        return fileItem.uid === file.uid
      });
      fileList.splice(index, 1);

      let aList = this.filearr
      let aIndex = aList.findIndex(fileItem => {
        return fileItem.uid === file.uid
      });
      this.filearr.splice(aIndex, 1)
    },
  }
}
</script>

<style>
#mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
}

.index {
  width: 980px;
  float: right;
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
}

.write {
  width: 700px;
  margin-bottom: 20px;
}

.slidedown {
  height: 40px;
  background-color: rgb(241, 248, 239);
  border-radius: 10px;
  cursor: pointer;
  position: relative;
  width: 700px;
}

.container .el-upload {
  float: right;
}

.innerit {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #e0c6a7;
  /*width: 700px;*/
}

.card {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 5px;
}

.logo {
  cursor: pointer;
}

.header {
  width: 700px;
  height: 40px;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  border-bottom: 1px solid #eaeaea;
  padding: 5px;
}

.name {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  margin-left: 10px;
}

.article {
  width: 700px;
  min-height: 20px;
  table-layout: fixed;
  display: inline-block;
  word-wrap: break-word;
  /*border-bottom: 1px solid #eaeaea;*/
  padding: 5px;
  text-indent: 2em;
  text-align: left;
}

.picture {
  width: 700px;
  min-height: 50px;
  border-bottom: 1px solid #eaeaea;
  padding: 5px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.operation {
  display: flex;
  flex-direction: row;
  justify-content: right;
  align-items: center;
  padding: 5px;
  margin-top: 10px;
}

.thumbs_up {
  height: 20px;
  width: 20px;
  background: url("../assets/赞.png") no-repeat;
  background-size: 20px 20px;
  cursor: pointer;
}

.thumbs_up:hover {
  height: 20px;
  width: 20px;
  background: url("../assets/赞_hover.png") no-repeat;
  background-size: 20px 20px;
  cursor: pointer;
}

.thumbs_up_red {
  height: 20px;
  width: 20px;
  background: url("../assets/赞_red.png") no-repeat;
  background-size: 20px 20px;
  cursor: pointer;
}

.thumbs_up_red:hover {
  height: 20px;
  width: 20px;
  background: url("../assets/赞_red_hover.png") no-repeat;
  background-size: 20px 20px;
  cursor: pointer;
}

.comment {
  height: 20px;
  width: 20px;
  background: url("../assets/评论.png") no-repeat;
  background-size: 20px 20px;
  cursor: pointer;
  margin-right: 20px;
}

.comment:hover {
  height: 20px;
  width: 20px;
  background: url("../assets/评论_hover.png") no-repeat;
  background-size: 20px 20px;
  cursor: pointer;
  margin-right: 20px;
}

.share {
  height: 20px;
  width: 20px;
  background: url("../assets/转发.png") no-repeat;
  background-size: 20px 20px;
  cursor: pointer;
  margin-right: 20px;
}

.share:hover {
  height: 20px;
  width: 20px;
  background: url("../assets/转发_hover.png") no-repeat;
  background-size: 20px 20px;
  cursor: pointer;
  margin-right: 20px;
}

.logodiv {
  border-radius: 50%;
}

.logodiv:before,
.logodiv:after {
  position: absolute;
  content: "";
  left: -5px;
  right: -5px;
  top: -5px;
  bottom: -5px;
  border: 5px solid #FF33FF;
}

.logodiv:before {
  animation: move 5s linear infinite;
}

.logodiv:after {
  border-color: #FF33FF;
  animation: move 5s linear infinite normal -2.5s;
}

@keyframes move {
  0%, 100% {
    clip: rect(0, 200px, 5px, 0);
  }
  25% {
    clip: rect(0, 200px, 200px, 195px);
  }
  50% {
    border-color: #00ff0088;
    clip: rect(195px, 200px, 200px, 0);
  }
  75% {
    clip: rect(0, 5px, 200px, 0px);
  }
}
</style>